/**
 * Created by Administrator on 2018/5/16.
 * 本js主要是用来从数组中获取相应的Hex数据及进行相应的处理
 */

var hexHelper = {
    //微信小游戏相关参数
    score:0,                                        //得分
    totalScore:0,                                   //最高得分
    scoreTxt:null,                                  //发送给子域的分数
    mainScene:null,                                 //排行榜显示场景

    //游戏相关参数
    allPositon : [],                                //记录所有六角形的位置(像素位置）
    allItems:{},                                    //所有转子信息对象，记录q-r信息
    allArrows  : [],                                //所有转子对象
    mineRate: 0,                                    //用来显示我方比例
    enemyRate: 0,                                   //用来显示敌方比例
    highestTimeoutId: 0,                            //延时操作的ID，暂时未用上保留
    pathNumber: 0,                                  //所有分支数量
    isAction: false,                                //我方是否在行动（一个回合，包括敌方)
    enemyPos: [],                                   //敌方占据的hex位置
    mineCount: 1,                                   //我方占据的数量
    enemyCount: 1,                                  //敌方占据的数量 和enemyPos的长度相等
    interval: 300,                                  //动画间隔 毫秒
    status:allEnum.status.None,                     //胜利还是输了
    isOver:false,                                   //本关是否结束

    //根据坐标获得数组中的Hex
    getHexByCoor: function (pos, hexs) {
        var result = null;
        for (var item in hexs) {
            if (pos.q == hexs[item].q && pos.r == hexs[item].r) {
                result = hexs[item];
                break;
            }
        }
        return result;
    },

    //处理点击选中的转子的旋转
    clickItem: function (baseItem) {
        //验证条件
        if(this.isOver)
            return;
        var index = baseItem.hexIndex;
        var hex = hexMap.allHex[index];
        if (hex.owner !== allEnum.owner.Mine)
            return;
        if (this.isAction)
            return;
        this.isAction = true;
        var self = this;
        var item = self.allArrows[index];
        var flag = global.orientation === allEnum.orientation.pointy ;
        var offset =  flag ? allConst.offset : 0;
        //旋转方向
        rotateHex(hex);
        this.pathNumber = 1;
        var _result = - hex.orientation * allConst.orientation_offset + offset;
        if(item.rotation >=offset){
            item.rotation = -6 * allConst.orientation_offset + offset;
        }
        //微秒步进一次，一
        var _timer = setInterval(function(){
            item.rotation += config.divisor;
            if(item.rotation >= _result){
                item.rotation = _result;
                clearInterval(_timer);
                self.dealLink(hex, false);
            }
        },config.timeout);
    },
    //计算连接路径
    dealLink: function (hex, isEnemy) {
        var self = this;
        var condition = isEnemy ? allEnum.owner.Enemy : allEnum.owner.Mine;
        var allNeighbours = [];
        //计算周围指向自己的方块
        if (!global.isOneWay)
            self.addNeighbour(hex, condition, allNeighbours);
        //加入自身指向方块
        self.addPoint(hex, condition, allNeighbours);
        self.pathNumber--;
        if (allNeighbours.length === 0)
            self.judgeEnd(isEnemy);
        else
            self.dealFill(allNeighbours, isEnemy);
    },
    //计算周围指向自己的方块
    addNeighbour: function (hex, condition, allNeighbours) {
        for (var i = 0; i < hex_directions.length; i++) {
            var tempHex = hex_neighbor(hex, i);
            var pointHex = this.getHexByCoor(tempHex, hexMap.allHex);
            if (!pointHex)
                continue;
            if (pointHex.owner === condition)
                continue;
            //获得有效相邻方块的指向，如果和本hex相等，则包含进去
            var newPointHex = hex_neighbor(pointHex, pointHex.orientation);
            if (hex_equal(newPointHex, hex))
                allNeighbours.push(pointHex);
        }
    },
    //加入自身指向方块，需要判断是否已经在里面了
    addPoint: function (hex, condition, allNeighbours) {
        var tempHex2 = hex_neighbor(hex, hex.orientation);
        var pointHex2 = this.getHexByCoor(tempHex2, hexMap.allHex);
        if (pointHex2 != null && pointHex2.owner !== condition) {
            var flag = false;
            for (var i = 0; i < allNeighbours.length; i++) {
                if (hex_equal(allNeighbours[i], pointHex2)) {
                    flag = true;
                    break;
                }
            }
            //为true代表已经在里面
            if (!flag)
                allNeighbours.push(pointHex2);
        }
    },
    //判断终止条件
    judgeEnd: function (isEnemy) {
        var self = this;
        if (this.pathNumber === 0) {
            var code = this.judgeWin();
            if (code !== allEnum.status.None) {
                this.status = code;
                this.isOver = true;
                //todo 出现输或赢面板按钮
                var win = new winBoard();
                this.mainScene.addChild(win);
                return;
            }

            if (isEnemy) {
                this.isAction = false;
            } else {
                //延时1秒执行敌方行动，是为了给玩家反应时间
                //这里增加提示：比如动画，
                self.highestTimeoutId = setTimeout(function () {
                    self.clickEnemyItem();
                }, config.delayTime * 3);
            }
        }
    },
    //处理填充
    dealFill: function (allNeighbours, isEnemy) {
        var self = this;
        if(self.isOver)
            return;
        var condition = isEnemy ? allEnum.owner.Enemy : allEnum.owner.Mine;
        self.pathNumber += allNeighbours.length;
        for (var i = 0; i < allNeighbours.length; i++) {
            var newHex = allNeighbours[i];
            var mes = newHex.q + "-" + newHex.r;
            var item = self.allItems[mes];
            var condition2 = !isEnemy ? allEnum.owner.Enemy : allEnum.owner.Mine;
            if (newHex.owner === condition2) {
                if (isEnemy) {
                    this.mineCount--;
                } else {
                    this.enemyCount--;
                    this.removeEnemyHex(newHex);
                }
            }
            newHex.owner = condition;
            if (isEnemy) {
                item["showArrow"].tint = hexMap.enemyColor;
                item["showHex"].tint = hexMap.enemyColor;
                this.enemyCount++;
                this.enemyPos.push(newHex);
            } else {
                item["showArrow"].tint = hexMap.mineColor;
                item["showHex"].tint = hexMap.mineColor;
                this.mineCount++;
            }

        }
        // music.stop();
        //todo 计算敌我双方比例
        //显示我方得分
        this.enemyRate.text = (this.enemyCount / this.allPositon.length * 100).toFixed(1) + "%";
        this.mineRate.text = (this.mineCount / this.allPositon.length * 100).toFixed(1) + "%";
        this.score = this.mineCount;
        this.scoreTxt.text = "" + this.score;
        //进行下一步递归
        flax.playSound(resource.res_expand);
        for (var i = 0; i < allNeighbours.length; i++) {
            var newHex = allNeighbours[i];
            this.delay(newHex, isEnemy);
        }
    },
    delay: function (p0, p1) {
        var self = this;
        self.highestTimeoutId = setTimeout(function () {
            self.dealLink(p0, p1);
        }, config.delayTime);
    },

    //判断输赢
    judgeWin: function () {
        if (this.enemyCount === 0 || this.mineCount / hexMap.allHex.length >= config.winRate) {
            return allEnum.status.Win;
        }
        if (this.mineCount === 0 || this.enemyCount / hexMap.allHex.length >= config.winRate) {
            return allEnum.status.Lose;
        }
        return allEnum.status.None;
    },
    //处理敌方行动，涉及到AI算法，故单独写出
    //此方法用来选中要转动的hex,并进行旋转
    clickEnemyItem: function () {
        var allRotateHexs = {
            rotate1: [],//记录一次转动能接触敌方
            rotate2: [],//两次
            rotate3: [],//三次
            rotate4: [],//四次
            rotate5: []//五次
        };
        this.calTimesOfRotation(allRotateHexs);
        var hex = this.getRandHex(allRotateHexs);
        if (!hex) {
            throw("错误，hex为空")
        }
        //旋转方向
        var item = this.allItems[hex.q + "-" + hex.r];
        var flag = global.orientation === allEnum.orientation.pointy ;
        var offset =  flag ? allConst.offset : 0;
        rotateHex(hex);
        this.pathNumber = 1;
        var self = this;
        var _result = - hex.orientation * allConst.orientation_offset + offset ;
        if(item.rotation >= offset){
            item.rotation = -6 * allConst.orientation_offset + offset;
        }
        var _timer = setInterval(function(){
            item.rotation += config.divisor;
            if(item.rotation >= _result){
                item.rotation = _result;
                clearInterval(_timer);
                self.dealLink(hex, true);
            }
        },config.timeout);
    },
    //分类统计各个块转动到接触敌方或空块所需要的次数
    calTimesOfRotation: function (allRotateHexs) {
        for (var i = 0; i < this.enemyPos.length; i++) {
            var hex = this.enemyPos[i];
            //这里进行预计算,得到可以转动的hex及需要转动的次数
            var newHex = Hex(hex.q, hex.r, hex.s);
            newHex.orientation = hex.orientation;
            for (var j = 1; j <= 5; j++) {
                rotateMulHex(newHex, j);
                var neighbourHex = hex_neighbor(newHex, newHex.orientation);
                var pointHex = this.getHexByCoor(neighbourHex, hexMap.allHex);
                if (pointHex != null && pointHex.owner !== allEnum.owner.Enemy) {
                    var mes = "rotate" + j;
                    allRotateHexs[mes].push(hex);
                    break;
                }
            }
        }
    },
    //从敌方可行动的hex中随机选择一个
    getRandHex: function (allRotateHexs) {
        var hex = null;
        for (var j = 1; j <= 5; j++) {
            var mes = "rotate" + j;
            var hexs = allRotateHexs[mes];
            if (hexs.length > 0) {
                var rand = Math.floor(hexs.length * Math.random());
                hex = hexs[rand];
                break;
            }
        }
        return hex;
    },
    //移除敌人位置数组里的数据
    removeEnemyHex: function (hex) {
        var index = -1;
        for (var i = 0; i < this.enemyPos.length; i++) {
            if (hex.q == this.enemyPos[i].q && hex.r == this.enemyPos[i].r) {
                index = i;
                break;
            }
        }
        if (index === -1) {
            console.log("出错了，请看log");
        } else {
            this.enemyPos.splice(index, 1);
        }
    },
    //重置相关变量
    reset: function () {
        this.pathNumber = 0;
        this.isAction = false;
        this.enemyPos = [];
        this.mineCount = 1;
        this.enemyCount = 1;
        for (var i = 0; i < this.highestTimeoutId; i++)
            clearTimeout(i);
        this.highestTimeoutId = 0;
        this.isOver = false;
    }
}
